package com.xdf.docmanagementsystem.common.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;

/**
 * @program: doc-management-system
 * @description: ehcache工具类
 * @author: Zhang
 * @create: 2020-06-28 08:23
 **/
public class EhCacheUtil {
    private static final String CONFIG_PATH = "/ehcache.xml";
    private static String CACHE_NAME = "store";
    private static CacheManager cacheManager;
    private static URL url;

    static {
        url = EhCacheUtil.class.getResource(CONFIG_PATH);
        cacheManager = CacheManager.create(url);
    }

    /**
     * 存入缓存
     *
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, String key, String value) {
        if (StringUtils.isEmpty(cacheName)) {
            cacheName = CACHE_NAME;
        }
        Cache cache = cacheManager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }


    /**
     * 获取缓存
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key) {
        if (StringUtils.isEmpty(cacheName)) {
            cacheName = CACHE_NAME;
        }
        if (StringUtils.isEmpty(key)) return null;
        Cache cache = cacheManager.getCache(cacheName);
        Element element = cache.get(key);
        if (element == null) return null;
        return element.getObjectValue();
    }

    /**
     * 删除缓存
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static boolean remove(String cacheName, String key) {
        if (StringUtils.isEmpty(key)) return false;
        Cache cache = cacheManager.getCache(cacheName);
        return cache.remove(key);
    }
}
